﻿using ControlzEx.Standard;
using GpCommon.Helpers;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace GPSpeedView.Views
{
    /// <summary>
    /// GPTopView.xaml 的交互逻辑
    /// </summary>
    public partial class GPTopView : Window
    {
        private double _height = 280;
        private double _width = 350;

        private TimeSpan _timeSpan = new TimeSpan(0, 15, 0);
        private DateTime _time;
        public GPTopView(DateTime time)
        {
            InitializeComponent();
            myCanvas.Height = _height;
            myCanvas.Width = _width;
            _time = time;
            InitData();
        }

        private void InitData()
        {
            try
            {
                myCanvas.Children.Clear();
                var size = GetTopCount(_time).Result;
                Thread.Sleep(100);
                var list = GetTopData(_time, size).Result;
                if (list.Count() < 2) return;
                double unitWidth = _width / list.Count();
                double unitHeight = (_height * 0.9) / list.Max();
                Random random = new Random();
                double x = 0.0;
                int total = 0;
                for (int i = 0; i < list.Count(); i++)
                {
                    Rectangle rectangle = new Rectangle();
                    rectangle.Width = unitWidth;
                    rectangle.Height = unitHeight * list[i];
                    rectangle.Fill = new SolidColorBrush(Color.FromRgb((byte)random.Next(255), (byte)random.Next(255), (byte)random.Next(255)));
                    myCanvas.Children.Add(rectangle);
                    Canvas.SetLeft(rectangle, x);
                    Canvas.SetTop(rectangle, _height - rectangle.Height);

                    Label label = new Label();
                    label.Content = list[i];
                    myCanvas.Children.Add(label);
                    Canvas.SetLeft(label, x);
                    Canvas.SetTop(label, _height - rectangle.Height - 20);

                    x += unitWidth;
                    total += list[i];
                }
                Label labelTotal = new Label();
                labelTotal.Content = total;
                myCanvas.Children.Add(labelTotal);
                Canvas.SetLeft(labelTotal, _width / 2);
                Canvas.SetTop(labelTotal, 10);
            }
            catch (Exception)
            {

            }

        }

        /// <summary>
        /// 获取涨停数
        /// </summary>
        /// <param name="day"></param>
        /// <param name="isToday"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public async Task<int> GetTopCount(DateTime time)
        {
            string url = UrlHelper.GetUrlForTodayTopGps(time, 20);

            int size = 0;
            List<ViewEntity> ents = new List<ViewEntity>();
            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage response = await client.GetAsync(url).ConfigureAwait(false);
                if (response.IsSuccessStatusCode)
                {
                    response.EnsureSuccessStatusCode();
                    string htmlContent = response.Content.ReadAsStringAsync().Result;
                    if (!string.IsNullOrEmpty(htmlContent))
                    {
                        JObject jobject = JObject.Parse(htmlContent);
                        if (string.IsNullOrEmpty(jobject["data"].ToString())) return 0;
                        var childrens = jobject["data"]["pool"].Children();
                        string totalStr = jobject["data"]["tc"].ToString();
                        if (!string.IsNullOrEmpty(totalStr))
                        {
                            int.TryParse(totalStr, out size);
                        }
                    }
                }
            }
            return size;
        }
        /// <summary>
        /// 获取涨停数据
        /// </summary>
        /// <param name="day"></param>
        /// <param name="isToday"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public async Task<int[]> GetTopData(DateTime time, int count)
        {
            string url = UrlHelper.GetUrlForTodayTopGps(time, count);
            var timeSpans = GetTimeSpans();
            int[] ents = new int[timeSpans.Count];
            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage response = await client.GetAsync(url).ConfigureAwait(false);
                if (response.IsSuccessStatusCode)
                {
                    response.EnsureSuccessStatusCode();
                    string htmlContent = response.Content.ReadAsStringAsync().Result;
                    if (!string.IsNullOrEmpty(htmlContent))
                    {
                        JObject jobject = JObject.Parse(htmlContent);
                        if (string.IsNullOrEmpty(jobject["data"].ToString())) return null;
                        var childrens = jobject["data"]["pool"].Children();
                        foreach (var item in childrens)
                        {
                            string timeStr = item["fbt"].ToString();
                            if (timeStr.Count() == 5)
                                timeStr = '0' + timeStr;
                            int hour = int.Parse(timeStr.Substring(0, 2));
                            int min = int.Parse(timeStr.Substring(2, 2));
                            int sec = int.Parse(timeStr.Substring(4, 2));
                            TimeSpan span = new TimeSpan(hour, min, sec);
                            for (int i = 0; i < timeSpans.Count; i++)
                            {
                                if (span >= timeSpans[i] && span < timeSpans[i] + _timeSpan)
                                {
                                    ents[i]++;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            return ents;
        }

        private List<TimeSpan> GetTimeSpans()
        {
            List<TimeSpan> list = new List<TimeSpan>();
            TimeSpan start = new TimeSpan(9, 15, 0);
            do
            {
                list.Add(start);
                start = start.Add(_timeSpan);
            } while (start < new TimeSpan(11,30,0));
            start = new TimeSpan(13, 0, 0);
            do
            {
                list.Add(start);
                start = start.Add(_timeSpan);
            } while (start < new TimeSpan(15, 0, 0));
            return list;
        }

    }
}
